from rest_framework.views import APIView, Response
from ..serializers.group_serializers import GroupSerializer
from ..models.login import GroupModel


class Group(APIView):
    def get(self, request):
        context = dict()
        context['err_code'] = 0
        data = request.GET
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        id = data.get('id')
        if id is None:
            context['err_code'] = 2001
            context['error'] = "请求参数不正确"
            return Response(context)
        query = GroupModel.objects.filter(id=id)
        if not query.exists():  # 请求数据不存在
            context['err_code'] = 3004
            context['error'] = "无法找到您要的数据"
            return Response(context)
        group = query.first()
        context['data']=GroupSerializer(group).data
        is_owner = (group.owner == user)
        is_manager=False
        for manager in group.managers.all():
            if manager==user:
                is_manager=True
        is_member=False
        for member in group.members.all():
            if member==user:
                is_member=True
        if is_owner or is_manager:
            pass
        else:
            if not is_member:
                del context['data']
                context['err_code']=3003
                context['error']="您无权查看此内容"

        return Response(context)

    def post(self, request):
        context = dict()
        context['err_code'] = 0
        data = request.POST
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
